#import "LoginScreen.h"

@interface LoginScreen ()

@property (weak, nonatomic) IBOutlet UIPickerView *usernamePicker;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;

@property NSTimer *usersTimer;

@property NSMutableArray* users;
@property NSString *usernameText;

@end
//78.90.20.186 wremenno IP
//95.111.78.55:8080
static NSString* kUsersUrl = @"http://78.90.20.186:8080/ProjectRestaurant/getWaiters";
static NSString* kLoginUrl = @"http://78.90.20.186:8080/ProjectRestaurant/LoginWaiter";

@implementation LoginScreen


- (IBAction)panic:(id)sender {
    [self performSegueWithIdentifier:@"LoginToTables" sender:self];
}

#pragma mark - View Setup

- (void) viewDidLoad {
    [super viewDidLoad];
    
    [self.passwordText becomeFirstResponder];
    
    //Listen for username updates
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(update:)
                                                 name:@"usernames" object:nil];
    
    self.navigationController.navigationBar.hidden = YES;
    
    self.usernamePicker.delegate = self;
    self.usernamePicker.dataSource = self;
    
    
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUserNames];
    self.usersTimer = [NSTimer timerWithTimeInterval:10.0 target:self selector:@selector(checkUsernames) userInfo:nil repeats:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.passwordText resignFirstResponder];
}

- (void) update:(NSNotification*) note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.usernamePicker reloadAllComponents];
        if ([self.users count] > 0) {
            self.usernameText = self.users[0];
        }
    });
}

#pragma mark - picker for login

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return  1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;{
    return [self.users count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.users[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if ([self.users count] > 0) {
        self.usernameText = self.users[row];
    }
}

-(void) getUserNames{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:kUsersUrl]];
    NSURLSessionDataTask* downloadJSONTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSError* mistake = nil;
        NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&mistake];
        
        if (mistake != nil) {
            NSLog(@"Error : %@", [mistake localizedDescription]);
        }
        else {
            self.users = [NSMutableArray arrayWithArray:jsonArray];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"usernames" object:self userInfo:nil];
        }
        
    }];
    [downloadJSONTask resume];
    
}

-(void) checkUsernames{
    if ([self.users count] == 0) {
        [self getUserNames];
    }
    else{
        [self.usersTimer invalidate];
        self.usersTimer = nil;
    }
}

#pragma mark - Login Networking

-(IBAction)setJsonFromData:(id)sender{
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:self.usernameText, @"username", self.passwordText.text, @"password", nil];

    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        NSError *error = nil;
        NSData *result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
        if (error == nil && result != nil) {
            NSData *response = [self jsonPostRequest:result];
            
            NSError* mistake = nil;
            NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&mistake];
                        
            if (mistake != nil) {
                NSLog(@"Error : %@", [mistake localizedDescription]);
            }
            else {
                if ([jsonDictionary[@"response"]isEqual:@"Wrong username or password!"]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong Password"
                                                                        message:@"Retry"
                                                                       delegate:self
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil];
                        [alert show];
                        self.passwordText.text = @"";
                    });
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self performSegueWithIdentifier:@"LoginToTables" sender:self];
                    });
                }
            }
        }
    }
}

-(id) jsonPostRequest:(NSData*) jsonRequestData{
    NSURL *url = [NSURL URLWithString:kLoginUrl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];
    
    //send synch request
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    
    if (error == nil) {
        return result;
    }
    else{
        return nil;
    }
}

@end
